// 定义树形数据的类型
export interface TreeNode {
    key: string
    title: string
    children?: TreeNode[]
    icon?: string
    isLeaf?: boolean
}

// 模拟数据库 - 存储所有树形数据（扁平化数组）
const treeDatabase: TreeNode[] = [
    // 根节点
    { key: 'root-1', title: '根节点', isLeaf: false },

    // 第一层子节点
    { key: 'root-1-1', title: '部门管理', isLeaf: false },
    { key: 'root-1-2', title: '用户管理', isLeaf: false },
    { key: 'root-1-3', title: '系统设置', isLeaf: false },
    { key: 'root-1-4', title: '数据统计', isLeaf: false },

    // 第二层子节点
    { key: 'root-1-1-1', title: '技术部', isLeaf: false },
    { key: 'root-1-1-2', title: '产品部', isLeaf: false },
    { key: 'root-1-1-3', title: '运营部', isLeaf: false },
    { key: 'root-1-1-4', title: '市场部', isLeaf: false },
    { key: 'root-1-1-5', title: '人事部', isLeaf: true },

    { key: 'root-1-2-1', title: '管理员', isLeaf: false },
    { key: 'root-1-2-2', title: '普通用户', isLeaf: false },
    { key: 'root-1-2-3', title: 'VIP用户', isLeaf: true },
    { key: 'root-1-2-4', title: '访客用户', isLeaf: true },

    { key: 'root-1-3-1', title: '基础设置', isLeaf: false },
    { key: 'root-1-3-2', title: '安全设置', isLeaf: false },
    { key: 'root-1-3-3', title: '通知设置', isLeaf: true },
    { key: 'root-1-3-4', title: '备份设置', isLeaf: true },

    { key: 'root-1-4-1', title: '用户统计', isLeaf: false },
    { key: 'root-1-4-2', title: '访问统计', isLeaf: false },
    { key: 'root-1-4-3', title: '业务统计', isLeaf: true },
    { key: 'root-1-4-4', title: '系统统计', isLeaf: true },

    // 第三层子节点
    { key: 'root-1-1-1-1', title: '前端开发', isLeaf: false },
    { key: 'root-1-1-1-2', title: '后端开发', isLeaf: false },
    { key: 'root-1-1-1-3', title: '测试工程师', isLeaf: true },
    { key: 'root-1-1-1-4', title: '运维工程师', isLeaf: true },
    { key: 'root-1-1-1-5', title: '架构师', isLeaf: true },

    { key: 'root-1-1-2-1', title: '产品经理', isLeaf: true },
    { key: 'root-1-1-2-2', title: 'UI设计师', isLeaf: true },
    { key: 'root-1-1-2-3', title: '交互设计师', isLeaf: true },
    { key: 'root-1-1-2-4', title: '数据分析师', isLeaf: true },

    { key: 'root-1-1-3-1', title: '内容运营', isLeaf: true },
    { key: 'root-1-1-3-2', title: '用户运营', isLeaf: true },
    { key: 'root-1-1-3-3', title: '活动运营', isLeaf: true },
    { key: 'root-1-1-3-4', title: '社区运营', isLeaf: true },

    { key: 'root-1-1-4-1', title: '市场推广', isLeaf: true },
    { key: 'root-1-1-4-2', title: '品牌策划', isLeaf: true },
    { key: 'root-1-1-4-3', title: '商务合作', isLeaf: true },
    { key: 'root-1-1-4-4', title: '媒体公关', isLeaf: true },

    { key: 'root-1-2-1-1', title: '超级管理员', isLeaf: true },
    { key: 'root-1-2-1-2', title: '系统管理员', isLeaf: true },
    { key: 'root-1-2-1-3', title: '数据管理员', isLeaf: true },
    { key: 'root-1-2-1-4', title: '安全管理员', isLeaf: true },

    { key: 'root-1-2-2-1', title: '注册用户', isLeaf: true },
    { key: 'root-1-2-2-2', title: '认证用户', isLeaf: true },
    { key: 'root-1-2-2-3', title: '活跃用户', isLeaf: true },
    { key: 'root-1-2-2-4', title: '沉默用户', isLeaf: true },

    { key: 'root-1-3-1-1', title: '语言设置', isLeaf: true },
    { key: 'root-1-3-1-2', title: '时区设置', isLeaf: true },
    { key: 'root-1-3-1-3', title: '主题设置', isLeaf: true },
    { key: 'root-1-3-1-4', title: '字体设置', isLeaf: true },

    { key: 'root-1-3-2-1', title: '密码策略', isLeaf: true },
    { key: 'root-1-3-2-2', title: '登录限制', isLeaf: true },
    { key: 'root-1-3-2-3', title: '权限控制', isLeaf: true },
    { key: 'root-1-3-2-4', title: '审计日志', isLeaf: true },

    { key: 'root-1-4-1-1', title: '用户增长', isLeaf: true },
    { key: 'root-1-4-1-2', title: '用户活跃度', isLeaf: true },
    { key: 'root-1-4-1-3', title: '用户留存率', isLeaf: true },
    { key: 'root-1-4-1-4', title: '用户流失率', isLeaf: true },

    { key: 'root-1-4-2-1', title: '页面访问', isLeaf: true },
    { key: 'root-1-4-2-2', title: '功能使用', isLeaf: true },
    { key: 'root-1-4-2-3', title: '停留时长', isLeaf: true },
    { key: 'root-1-4-2-4', title: '跳出率', isLeaf: true },

    // 第四层子节点
    { key: 'root-1-1-1-1-1', title: 'Vue开发', isLeaf: true },
    { key: 'root-1-1-1-1-2', title: 'React开发', isLeaf: true },
    { key: 'root-1-1-1-1-3', title: 'Angular开发', isLeaf: true },
    { key: 'root-1-1-1-1-4', title: '小程序开发', isLeaf: true },
    { key: 'root-1-1-1-1-5', title: '移动端开发', isLeaf: true },

    { key: 'root-1-1-1-2-1', title: 'Java开发', isLeaf: true },
    { key: 'root-1-1-1-2-2', title: 'Python开发', isLeaf: true },
    { key: 'root-1-1-1-2-3', title: 'Node.js开发', isLeaf: true },
    { key: 'root-1-1-1-2-4', title: 'Go开发', isLeaf: true },
    { key: 'root-1-1-1-2-5', title: 'PHP开发', isLeaf: true }
]

// 模拟网络延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

// 获取子节点
export const fetchNodes = async (parentKey?: string): Promise<TreeNode[]> => {
    await delay(800);

    if (!parentKey) {
        return treeDatabase.filter(({ key }) => key === 'root-1');
    }

    return treeDatabase.filter(node => {
        const nodeKeyParts = node.key.split('-')
        const parentKeyParts = parentKey.split('-')

        // 子节点的key应该比父节点多一个部分
        return nodeKeyParts.length === parentKeyParts.length + 1 &&
            node.key.startsWith(parentKey + '-')
    })
}

// 模拟API请求 - 删除节点
export const deleteNode = async (nodeKey: string) => {
    await delay(300)

    const nodeIndex = treeDatabase.findIndex(node => node.key === nodeKey)
    if (nodeIndex === -1) {
        throw new Error('节点不存在')
    }

    const indicesToDelete: number[] = []
    treeDatabase.forEach((node, index) => {
        if (node.key === nodeKey || node.key.startsWith(nodeKey + '-')) {
            indicesToDelete.push(index)
        }
    })

    // 从后往前删除，避免索引变化
    indicesToDelete.reverse().forEach(index => {
        treeDatabase.splice(index, 1)
    })

    console.log(`删除了 ${indicesToDelete.length} 个节点`)
}

// 搜索节点并返回完整路径（只返回第一个匹配的节点）
export const searchNode = async (searchText: string): Promise<{ node: TreeNode; paths: string[] } | null> => {
    await delay(300)

    // 查找第一个匹配的节点
    const matchedNode = treeDatabase.find(node =>
        node.title.toLowerCase().includes(searchText.toLowerCase())
    )

    if (!matchedNode) {
        return null;
    }

    const paths = buildNodePath(matchedNode.key)
    return { node: matchedNode, paths }
}

// 根据节点key构建从根节点到其父节点的路径
const buildNodePath = (nodeKey: string): string[] => {
    const paths: string[] = ['root-1'];
    const keyParts = nodeKey.slice('root-1-'.length).split('-')

    // 构建路径
    for (const key of keyParts) {
        const currentKey = `${paths[paths.length - 1]}-${key}`;
        const node = treeDatabase.find(({ key }) => key === currentKey && key !== nodeKey)
        if (node) {
            paths.push(node.key)
        }
    }

    return paths
}